/**
 * Created by Administrator on 2015/12/14.
 */

var express = require('express');
var router = express.Router();
var BaseModel = require('../models/base_model');
var baseModel = new BaseModel();
var CheckLogin = require('../models/checkLogin');
var checkLogin =new CheckLogin();
var async = require('async');


router.get('/',checkLogin.check);

router.get('/', function(req, res) {
   res.render('great_ip',{
       title:'生成IP地址池',
       cook_name:req.cookies.IP,
       msg:''
   });
});

router.post('/',checkLogin.check);

router.post('/',function(req,res) {
    var tableName = 'ips';
    var rowInfo = {};
    var c_Lan = req.body.ip1 + '.' + req.body.ip2 + '.' + req.body.ip3;

    async.series([
        function bool_check(callback)
        {
            var sql = "select count(id) as co from ips where c_lan='" + c_Lan + "'";
            baseModel.findOneById(sql, function (ret) {
                callback(null,ret.co);
            });
        }
    ],
    function(err, results) {
      var message;
      console.log(results);
      if(results=='0')
      {
          for (var i = 1; i <= 255; i++) {
              rowInfo =
              {
                  'ip_name': c_Lan + '.' + i,
                  'c_lan': c_Lan,
                  'states': '未用'
              };
              baseModel.insert(tableName, rowInfo, function (ret) {
              })
          }
          message='地址池创建成功';
      }
      else {
          message='地址池已经存在';
      }

      var sql = "select * from ips where c_Lan='" + c_Lan + "'";
      console.log(sql);
      baseModel.findMoreById(sql, function (ret) {
          res.render('great_ip', {
                title: '主页',
                content: ret,
                cook_name: req.cookies.IP,
                msg: message
            });
      });
    }
 );

})



module.exports = router;